package com.onlyphoto.onlymall.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatRadioButton
import androidx.core.content.ContextCompat
import com.onlyphoto.onlymall.R


/**
 * @Author:chy
 * @Date: 2018-06-21 18:42
 * @Description:
 */

class RedDotRadioButton : AppCompatRadioButton {

    // 重新绘制
    private var isTipOn = false

    fun setRedOn(tip: Boolean) {
        isTipOn = tip
        invalidate()
    }

    private var mDot: Dot? = null

    constructor(context: Context) : super(context) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init()
    }

    private fun init() {
        mDot = Dot()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        if (this.isTipOn) {
            var cx = (width - mDot!!.radius).toFloat()
            val cy = mDot!!.radius.toFloat() + mDot!!.marginTop.toFloat()

            val drawableTop = compoundDrawables[1]
            if (drawableTop != null) {
                val drawableTopWidth = drawableTop.intrinsicWidth
                if (drawableTopWidth > 0) {
                    val dotLeft = width / 2 + drawableTopWidth / 2 - mDot!!.radius
                    cx = dotLeft.toFloat() + mDot!!.marginLeft
                }
            }

            val paint = paint
            //save
            val tempColor = paint.color

            paint.color = mDot!!.color
            paint.style = Paint.Style.FILL
            canvas.drawCircle(cx, cy, mDot!!.radius.toFloat(), paint)

            //restore
            paint.color = tempColor
        }
    }

    private inner class Dot internal constructor() {

        internal var color: Int = 0

        internal var radius: Int = 0

        internal var marginTop: Int = 0

        internal var marginLeft: Int = 0

        init {
            val density = context.resources.displayMetrics.density
            radius = (4 * density).toInt()
            marginTop = (5 * density).toInt()
            marginLeft = (4 * density).toInt()

            color = ContextCompat.getColor(context, R.color.red)
        }

    }
}
